package com.silverhaze.diamond.client.utils.db.engines;

import com.silverhaze.commons.db.datasource.ObjectEntity;
import com.silverhaze.diamond.client.utils.db.ServiceDataSource;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author: Ivan Babanin
 * Time: 6:16:25
 * Date: 22.05.2008
 * <p/>
 * This part of code is strictly confidential.
 */
public class CachingEngine {

    private static boolean enable = false;
    private static Map<Class, List<ObjectEntity>> cache = new HashMap<Class, List<ObjectEntity>>();

    static {
        reload();
    }

    public static void reload() {
        ServiceDataSource dataSource = ServiceDataSource.getInstance();

        for (Class clazz : cache.keySet()) {
            cache.put(clazz, dataSource.getBeans(clazz));
        }
    }

    public static void reload(Class clazz) {
        cache.put(clazz, ServiceDataSource.getInstance().getBeans(clazz));
    }

    public static void persist(ObjectEntity o) {
        List<ObjectEntity> objs = cache.get(o.getClass());

        if (objs != null) {
            ObjectEntity sameObj = findObject(o, objs);
            if (sameObj != null) {
                objs.remove(sameObj);
            }

            objs.add(o);
        }
    }

    private static ObjectEntity findObject(ObjectEntity o, List<ObjectEntity> objs) {
        for (ObjectEntity objectEntity : objs) {
            if (objectEntity.getId() == o.getId()) {
                return objectEntity;
            }
        }

        return null;
    }

    public static boolean isCacheEnabled() {
        return enable;
    }

    public static void remove(ObjectEntity entity) {
        List<ObjectEntity> entities = cache.get(entity.getClass());

        if (entities != null) {
            entities.remove(entity);
        }
    }

    public static List getBeans(Class clazz) {
        return cache.get(clazz);
    }

    public static void commit() {
        ServiceDataSource dataSource = ServiceDataSource.getInstance();

        for (List<ObjectEntity> list : cache.values()) {
            if (list.size() > 0) {
                dataSource.clean(list.get(0).getClass());
                for (ObjectEntity entity : list) {
//                    dataSource.persist();
                }
            }
        }
    }
}

